package com.demomaster.quickcompat.widget;

import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CompoundButton;

import androidx.annotation.IdRes;

import com.demomaster.quickcompat.widget.layout.FlowLayout;


/**
 * 支持多选（多选数量）和单选
 */
public class QuickCheckBoxGroup extends FlowLayout {

    private static final String TAG = "QuickCheckBoxGroup";

    public enum CheckType {
        //notLimit数量不限 mandatoryLimit数量必选 rangeLimit数量范围
        notLimit,
        mandatoryLimit,
        rangeLimit
    }

    private boolean isSingle;//是否是单选
    private int fixedSelectCount = 1;//固定可选数量 适用于mandatoryLimit模式
    private int minSelectCount = 0;//可选最小数量 适用于rangeLimit模式
    private int maxSelectCount = Integer.MAX_VALUE;//可选最大数量 适用于rangeLimit模式
    private CheckType checkType = CheckType.notLimit;

    public CheckType getCheckType() {
        return checkType;
    }

    public void setCheckType(CheckType checkType) {
        this.checkType = checkType;
    }

    public void setMinSelectCount(int minSelectCount) {
        this.minSelectCount = minSelectCount;
    }

    public int getMinSelectCount() {
        return minSelectCount;
    }

    public int getMaxSelectCount() {
        return maxSelectCount;
    }

    public void setMaxSelectCount(int maxSelectCount) {
        this.maxSelectCount = maxSelectCount;
    }

    public boolean isSingle() {
        boolean b = false;
        switch (checkType) {
            case notLimit:
                b = isSingle;
                break;
            case rangeLimit:
                b = (maxSelectCount == minSelectCount && minSelectCount == 1) || (minSelectCount == 0 && maxSelectCount == 1);
                break;
            case mandatoryLimit:
                b = (fixedSelectCount == 1);
                break;
        }
        return b;
    }

    public void setSingle(boolean single) {
        isSingle = single;
    }

    public int getFixedSelectCount() {
        return fixedSelectCount;
    }

    public void setFixedSelectCount(int fixedSelectCount) {
        this.fixedSelectCount = fixedSelectCount;
        checkType= CheckType.mandatoryLimit;
        Log.i(TAG,getTag()+",setFixedSelectCount="+fixedSelectCount);
    }

    //获取当前已选项数量
    public int getCurrentSelectCount() {
        int currentSelectCount = 0;
        int count = getChildCount();
        for (int i = 0; i < count; i++) {
            View childView = getChildAt(i);
            if (childView instanceof CompoundButton) {
                if (((CompoundButton) childView).isChecked()) {
                    currentSelectCount = currentSelectCount + 1;
                }
            }else if (childView instanceof QuickCheckBoxLayout) {
                if (((QuickCheckBoxLayout) childView).isChecked()) {
                    currentSelectCount = currentSelectCount + 1;
                }
            }
        }
        return currentSelectCount;
    }

    public QuickCheckBoxGroup(Context context) {
        super(context);
        init();
    }

    public QuickCheckBoxGroup(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public QuickCheckBoxGroup(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    public void init() {
        setOnHierarchyChangeListener(onHierarchyChangeListener);
    }

    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();
        initView();
    }

    void initView() {
        int count = getChildCount();
       //QDLogger.println("initView... count=" + count);
        for (int i = 0; i < count; i++) {
            View childView = getChildAt(i);
            setChildrenListener(childView);
        }
    }

    private OnHierarchyChangeListener onHierarchyChangeListener = new OnHierarchyChangeListener() {
        @Override
        public void onChildViewAdded(View parent, View child) {
            //QDLogger.d("Added:"+child.getId());
            setChildrenListener(child);
        }

        @Override
        public void onChildViewRemoved(View parent, View child) {
            //QDLogger.d("Removed");
            if (child instanceof CompoundButton) {
                ((CompoundButton) child).setOnCheckedChangeListener(null);
            } else if (child instanceof QuickCheckBoxLayout) {
                ((QuickCheckBoxLayout) child).setOnCheckedChangeListener(null);
            }
        }
    };

    private void setChildrenListener(View child) {
        //QDLogger.println("setChildrenListener... parent=" + child);
        View childView = child;
        if (childView instanceof CompoundButton) {
            ((CompoundButton) childView).setOnCheckedChangeListener(innerOnCheckedChangeListener);
        } else if (childView instanceof QuickCheckBoxLayout) {
            ((QuickCheckBoxLayout) childView).setOnCheckedChangeListener(innerOnCheckedChangeListener);
        }
    }

    public void outOfMaxSelectCount(int maxSelectCount) {
    }
    boolean outOfMaxReplace;//超过最大数量 是否替换

    public void setOutOfMaxReplace(boolean outOfMaxReplace) {
        this.outOfMaxReplace = outOfMaxReplace;
    }

    OnCheckedChangeListener mOnCheckedChangeListener;
    public void setOnCheckedChangeListener(OnCheckedChangeListener onCheckedChangeListener) {
        this.mOnCheckedChangeListener = onCheckedChangeListener;
    }

    public interface MyOnCheckedChangeListener extends CompoundButton.OnCheckedChangeListener {
        void onCheckedChanged(QuickCheckBoxGroup group, boolean isChecked, @IdRes int changedViewId);
        void onCheckedChanged(ViewGroup group, boolean isChecked, @IdRes int changedViewId, QuickCheckBoxLayout quickCheckBoxLayout);
    }

    public static abstract class OnCheckedChangeListener implements MyOnCheckedChangeListener {

        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            onCheckedChanged((ViewGroup) buttonView.getParent(), isChecked, buttonView.getId(), null);
        }

        @Override
        public void onCheckedChanged(QuickCheckBoxGroup group, boolean isChecked, @IdRes int changedViewId) {
            //onCheckedChanged(group,isChecked,changedViewId,quickCheckBoxLayout);
            onCheckedChanged(group, isChecked, changedViewId, null);
        }
        //public abstract void onCheckedChanged(ViewGroup group, boolean isChecked, @IdRes int changedViewId, QuickCheckBoxLayout quickCheckBoxLayout);
    }

    private void setCheckedStateForView(View buttonView, boolean isChecked) {
        int id = buttonView.getId();
        if (isChecked) {
            if (isSingle()
                    || (checkType == CheckType.mandatoryLimit && fixedSelectCount == 1)
                    || (checkType == CheckType.rangeLimit && (minSelectCount == 1 && maxSelectCount == 1))) {
                Log.i(TAG,"单选");
                //处理单选的情况
                int count = getChildCount();
                for (int i = 0; i < count; i++) {
                    View childView = getChildAt(i);
                    Log.i(TAG,i+")button="+buttonView.getClass().getName()+buttonView.getId()+",childView="+childView.getClass().getName()+childView.getId());
                    if (childView.getId() != buttonView.getId()) {
                        if (childView instanceof CompoundButton) {
                            ((CompoundButton) childView).setChecked(false);
                        } else if (childView instanceof QuickCheckBoxLayout) {
                            //QDLogger.println("buttonView setChecked(false)");
                            ((QuickCheckBoxLayout) childView).setChecked(false);
                        }
                    }
                }
            }
        }
        if (checkType == CheckType.mandatoryLimit) {//限定数量
            Log.i(TAG,"3 ，fixedSelectCount="+fixedSelectCount);
            if (fixedSelectCount < getCurrentSelectCount()) {
                if (buttonView instanceof CompoundButton) {
                    ((CompoundButton) buttonView).setChecked(false);
                } else if (buttonView instanceof QuickCheckBoxLayout) {
                    ((QuickCheckBoxLayout) buttonView).setChecked(false);
                }
                outOfMaxSelectCount(fixedSelectCount);
                return;
            }
        } else if (checkType == CheckType.rangeLimit) {//
            if (maxSelectCount < getCurrentSelectCount()) {
                Log.i(TAG,"4");
                if (buttonView instanceof CompoundButton) {
                    ((CompoundButton) buttonView).setChecked(false);
                } else if (buttonView instanceof QuickCheckBoxLayout) {
                    ((QuickCheckBoxLayout) buttonView).setChecked(false);
                }
                outOfMaxSelectCount(maxSelectCount);
            }
        }
    }

    OnCheckedChangeListener innerOnCheckedChangeListener = new OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(ViewGroup group, boolean isChecked, int changedViewId, QuickCheckBoxLayout quickCheckBoxLayout) {
            if (mOnCheckedChangeListener != null) {
                mOnCheckedChangeListener.onCheckedChanged(group, isChecked, changedViewId, quickCheckBoxLayout);
            }
            if (quickCheckBoxLayout != null) {
                Log.i(TAG,"选择变更-31 isChecked=" + isChecked + ",changedViewId=" + changedViewId + ",group=" + group);
                setCheckedStateForView(quickCheckBoxLayout, isChecked);
            } else {
                Log.i(TAG,"选择变更-32 isChecked=" + isChecked + ",changedViewId=" + changedViewId + ",group=" + group);
                setCheckedStateForView(group.findViewById(changedViewId), isChecked);
            }
        }
    };

}
